﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.ApplyCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.ApplyHandler
{
    public class UpdApplyCommandHandler : IRequestHandler<UpdApplyCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Apply> _ApplyRepository;
        private readonly IMapper _mapper;

        public UpdApplyCommandHandler(IBaseRepository<Apply> applyRepository, IMapper mapper)
        {
            _ApplyRepository = applyRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(UpdApplyCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.Success;
            result.Msg = "修改成功";

            var apply = _ApplyRepository.GetAll().FirstOrDefault(p => p.ApplyId == request.ApplyId);
            if (apply != null)
            {
                apply.ApplyPerson = request.Name;
                apply.DepartmentId = request.DepartmentId;
                apply.LeaveType = request.LeaveType;
                apply.fristTime = request.fristTime;
                apply.EndTime = request.EndTime;
                apply.TotalTime = request.TotalTime;
                apply.CheckTime = request.CheckTime;
                apply.Reason = request.Reason;
                apply.UpUserId = request.UpUserId;
                apply.ApprovalStatusId = (int)ApprovalStatus.待审核;
                apply.ApprovalStatusName = ApprovalStatus.待审核.ToString();

                apply.UpdateTime = DateTime.Now;
                apply.UpdateUser = request.Name;
                apply.IsDeleted = false;

                _ApplyRepository.Update(apply);
            }

            return await Task.FromResult(result);
        }
    }
}
